<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="厂家品牌名" prop="brandName" class="single-line-label">-->
<!--        <el-select v-model="queryParams.brandName" placeholder="请选择厂家品牌名" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.check_type"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="检查类型名" prop="checkName" class="single-line-label">
        <el-select v-model="queryParams.checkName" placeholder="请选择检查类型名" clearable>
          <el-option
            v-for="dict in checkNameList"
            :key="dict.checkId"
            :label="dict.checkName"
            :value="dict.checkName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否开启" prop="isOpen">
        <el-select v-model="queryParams.isOpen" placeholder="请选择是否开启" clearable>
          <el-option
            v-for="dict in dict.type.is_open"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="是否删除" prop="isDeleted">-->
<!--        <el-select v-model="queryParams.isDeleted" placeholder="请选择是否删除" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.is_deleted"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['analysis:report:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['analysis:report:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['analysis:report:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['analysis:report:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

<!--   列表 -->

    <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="上传报告文件" align="center" prop="reportId" />
      <el-table-column label="厂家，品牌名" align="center" prop="brandName">
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.check_type" :value="scope.row.brandName"/>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="检查类型名" align="center" prop="checkName">
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.check_type" :value="scope.row.checkName"/>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="上传报告文件份数" align="center" prop="reportId" />
      <el-table-column label="是否开启" align="center" prop="isOpen">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_open" :value="scope.row.isOpen"/>
        </template>
      </el-table-column>
      <el-table-column label="是否选用通用模板" align="center" prop="isGeneral">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_select_template" :value="scope.row.isGeneral"/>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="修改" placement="top-start">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['analysis:report:edit']"
          >修改</el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="策略报告" placement="top-start">
              <el-button icon="el-icon-info"
                         type="text"
                         size="mini"
                         @click="goToStrategyDetail(scope.row)">策略报告
              </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报告文件信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="检查类型名" prop="checkName">
          <el-select v-model="form.checkName"
                     placeholder="请选择检查类型名"
                     clearable
                     filterable @change="getBrandList">
            <el-option
              v-for="dict in brandAndStrategyList"
              :key="dict.checkId"
              :label="dict.checkName"
              :value="dict.checkName"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 2. 是否选用通用模板 -->
        <el-form-item label="是否选用通用模板" prop="isGeneral">
          <el-select v-model="form.isGeneral" placeholder="请选择" @change="handleTemplateChange">
            <el-option
              v-for="dict in dict.type.is_select_template"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="厂家，品牌名" prop="brandName">
          <el-select v-if ="form.isGeneral === 1 "
                     v-model="form.brandName"
                     placeholder="请选择厂家，品牌名"
                     clearable
                     filterable @change="getStrategyList">
            <el-option
              v-for="dict in brandList"
              :key="dict.brandId"
              :label="dict.brandName"
              :value="dict.brandName"
            ></el-option>
          </el-select>
          <el-input
            v-else
            v-model="form.brandName"
            placeholder="请输入厂家、品牌名"
            ></el-input>
        </el-form-item>

        <el-form-item label="策略名称" prop="strategyName">
          <el-select v-if ="form.isGeneral === 1 "
                     v-model="form.strategyName"
                     placeholder="请选择策略名称">
            <el-option
              v-for="dict in strategyList"
              :key="dict.strategyBrandId"
              :label="dict.strategyName"
              :value="dict.strategyName"
            ></el-option>
          </el-select>
          <el-input
            v-else
            v-model="form.strategyName"
            placeholder="请输入策略名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否开启" prop="isOpen">
          <el-select v-model="form.isOpen" placeholder="请选择是否开启">
            <el-option
              v-for="dict in dict.type.is_open"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReport, getReport, delReport, addReport, updateReport } from "@/api/analysis/report"
import {getCheckNameList,selectBrandAndStrategyNameList} from "@/api/analysis/brand";

export default {
  name: "Report",
  dicts: ['is_deleted', 'check_type', 'is_open', 'is_select_template'],
  data() {
    return {
      // 检查类型列表
      checkNameList: [],
      // 获取品牌和策略列表
      brandAndStrategyList: [],
      // 品牌名列表
      brandList: [],
      // 策略名称列表
      strategyList: [],
      // 控制文件是否上传可用
      isFileUploadEnabled: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报告文件信息表格数据
      reportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        brandName: null,
        checkName: null,
        isOpen: null,
        isDeleted: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        brandName: [
          { required: true, message: "厂家、品牌名不能为空", trigger: "blur" }
        ],
        checkName: [
          { required: true, message: "检查类型名不能为空", trigger: "change" }
        ],
        isGeneral: [
          { required: true, message: "是否选用通用模板不能为空", trigger: "change" }
        ],
        strategyName: [
          { required: true, message: "策略名称不能为空", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.acquireCheckNameList()
    this.acquireBrandAndStrategyList()
  },
  methods: {
    handleTemplateChange(value) {
      // 切换模板类型时清空已选/已填内容
      this.form.brandName = '';
      this.form.strategyName = '';
    },
    // 跳转到数据页面
    goToReportDetail(row) {
      const {brandId, checkId, reportId} = row;
      let routePath = '';
      let queryParams = {};
      // 根据 checkId 决定跳转路径
      switch (parseInt(checkId)) {
        case 1:
          routePath = '/abpm/abpmReport'; // 动态心电页面路径
          break;
        case 2:
          routePath = '/dynamic-pressure'; // 动态血压页面路径
          break;
        case 3:
          routePath = '/oae/oaeReport'; // 耳声发射页面路径
          break;
        case 4:
          routePath = '/abr/abrReport';  // 听性脑干反应
          break;
        case 5:
          routePath = '/pta/ptaReport'; // 电测听页面路径
          break;
        case 6:
          routePath = '/aim/aimReport'; // 声导抗页面路径
          break;
        case 7:
          routePath = '/vng/vngReport'; // 眼震图页面路径
          break;
        case 8:
          routePath = '/hit/hitReport'; // 前庭功能检查页面路径
          break;
        case 9:
          routePath = '/bmd/bmdreport';    // 骨密码页面路径
          break;
        default:
          this.$message.error('未知的检查类型');
          return;
      }
      // 执行路由跳转
      this.$router.push({
        path: routePath,
        query: {brandId, checkId,reportId}
      });
      // this.$router.push('/bmd/bmdreport')
    },

    // 跳转到策略页面
    goToStrategyDetail(row) {
      // 解构参数并验证
      const {brandId, checkId, reportId} = row;

      // const {brandId, checkId, reportId} = row;
      let routePath = '';
      let queryParams = {};

      // 根据 checkType 决定跳转路径
      switch (parseInt(checkId)) {
        case 1:
          routePath = '/abpm/abpmReport'; // 动态心电页面路径
          break;
        case 2:
          routePath = '/dynamic-pressure'; // 动态血压页面路径
          break;
        case 3:
          routePath = '/oae/oaeReport'; // 耳声发射页面路径
          break;
        case 4:
          routePath = '/abr/abrReport';  // 听性脑干反应
          break;
        case 5:
          routePath = '/pta/ptaReport'; // 电测听页面路径
          break;
        case 6:
          routePath = '/aim/aimReport'; // 声导抗页面路径
          break;
        case 7:
          routePath = '/vng/vngReport'; // 眼震图页面路径
          break;
        case 8:
          routePath = '/hit/hitReport'; // 前庭功能检查页面路径
          break;
        case 9:
          routePath = '/bmd/bmdStrategy';    // 骨密码页面路径
          break;
        default:
          this.$message.error('未知的检查类型');
          return;
      }
      // 执行路由跳转
      this.$router.push({
        path: routePath,
        query: {brandId:brandId,
            checkId:checkId,
            reportId:reportId}
      });
      // this.$router.push('/bmd/bmdStrategy')
    },

    // 获取医院列表
    acquireCheckNameList() {
      getCheckNameList('').then(response => {
        // 示例数据，实际应根据查询结果返回
        this.checkNameList = response.data
      })
    },
    // 获取品牌和策略列表
    acquireBrandAndStrategyList() {
      selectBrandAndStrategyNameList('').then(response => {
        // 示例数据，实际应根据查询结果返回
        this.brandAndStrategyList = response.data
      })
    },

    /**
     * 选择检查类型，品牌名同步
     *
     */
    getBrandList() {
      const selectedBrandList = this.brandAndStrategyList.find(
        brandName => brandName.checkName === this.form.checkName
      )
      this.brandList = selectedBrandList ? selectedBrandList.brandNameVoList : null
    },

    /**
     * 选择品牌名后，同步策略名称列表
     *
     */
    getStrategyList() {
      const selectedBrandStrategyList = this.brandList.find(
        strategyName => strategyName.brandName === this.form.brandName
      )
      this.strategyList = selectedBrandStrategyList ? selectedBrandStrategyList.strategyNameVoList : null
    },
    // 报告文本信息详情页
    handleJump() {
      this.$router.push({ name: 'reportData' })
    },

    /** 查询报告文件信息列表 */
    getList() {
      this.loading = true
      listReport(this.queryParams).then(response => {
        this.reportList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.$refs.form.resetFields();
      this.isFileUploadEnabled = false;
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        reportId: null,
        reportFile: null,
        brandId: null,
        brandName: null,
        checkId: null,
        checkName: null,
        strategyName: null,
        isGeneral: null,
        isOpen: 1,
        createTime: null,
        updateTime: null,
        isDeleted: 0
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.reportId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.acquireCheckNameList();
      this.acquireBrandAndStrategyList();
      this.open = true
      this.title = "添加报告文件信息"
      this.acquireBrandAndStrategyList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.acquireCheckNameList();
      this.acquireBrandAndStrategyList();
      const reportId = row.reportId || this.ids
      getReport(reportId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改报告文件信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 1. 获取checkId
          // 获取检查类型Id
          const selectedCheckName = this.checkNameList.find(
            check => check.checkName === this.form.checkName
          )
          const Id = selectedCheckName ? selectedCheckName.checkId : null
          this.form.checkId = Id
          // 2. 获取brandId
          const selectBrandName = this.strategyList.find(
            brand => brand.strategyName === this.form.strategyName
          )
          const bId = selectBrandName ? selectBrandName.strategyBrandId : null
          this.form.brandId = bId
          if (this.form.reportId != null) {
            updateReport(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addReport(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const reportIds = row.reportId || this.ids
      this.$modal.confirm('是否确认删除报告文件信息编号为"' + reportIds + '"的数据项？').then(function() {
        return delReport(reportIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('analysis/report/export', {
        ...this.queryParams
      }, `report_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>


<style scoped>
/deep/ .single-line-label .el-form-item__label {
  white-space: nowrap;
}


.modal {
  transform: scale(1.2); /* 放大20% */
  transform-origin: center center;
}


.modal.large {
  padding: 30px; /* 增大内边距 */
}

.modal.large .form-item {
  margin-bottom: 20px; /* 增大表单项间距 */
}

.modal.large input,
.modal.large select {
  padding: 10px; /* 增大输入框内边距 */
  font-size: 16px; /* 增大字体 */
}
</style>
